<?php

/**
 * Description of Image
 *
 * @author Kam
 */
class My_Form_Element_ImageUpload extends Zend_Form_Element_File {

    protected $_sourceName;
    protected $_sourceId;

    public function init() {
        $this->initAttribs();
    }

    public function initAttribs() {
        $this->setAttrib('class', 'image-upload');
    }

    public function uploadFile() {
        if (!My_Utils::getController()->getRequest()->isPost()) {
            return;
        }
        $daoImage = new Application_Model_DAO_Image();
        $removed = null;
        if (!empty($this->_value) && $this->_value > 0) {
            $removed = $daoImage->get((int) $this->_value);
            $daoImage->delete((int) $this->_value);
            $this->_value = null;
        }
        $code = $_POST[$this->getId() . '_code'];
        $image = $daoImage->getByCode($code);
        $this->_value = $image['image_id'];
        if (!empty($_POST[$this->getId() . '_remove']) && $_POST[$this->getId() . '_remove'] == 1 && !empty($code)) {
            $daoImage->delete($code, 'code');
            $this->_value = null;
        }

        $upload = new Zend_File_Transfer_Adapter_Http();
        $uploadDir = My_Utils::buildTempPath(null, 'image');
        $info = $upload->getFileInfo();
        $info = $info[$this->getId()];
        $filename = $info['name'];
        $ext = strtolower(pathinfo($info['name'], PATHINFO_EXTENSION));
        $upload->addFilter('Rename', $uploadDir . '/iu-' . uniqid() . '.' . $ext);
        $isReceived = $upload->receive($this->getId());
        if (!$isReceived) {
            return;
        }

        // remove existing image
        if (!empty($code)) {
            $daoImage->delete($code, 'code');
        }

        $info = $upload->getFileInfo();
        $info = $info[$this->getId()];
        $image = $daoImage->addNew($info['tmp_name'], array(
            'user_id' => My_Utils::getCurrentUserId(),
            'active' => 0,
            'source_name' => $this->getSourceName(),
            'source_id' => $this->getSourceId(),
            'filename' => $filename,
                ));
        $this->setValue($image['image_id']);
    }

    public function getValue() {
        $this->uploadFile();
        $d = $this->_value;
        return $d;
    }

    public function setValue($value) {
        $this->_value = $value;
        return $this;
    }

    public function render(Zend_View_Interface $view = null) {
        $this->initAttribs();
        return parent::render($view);
    }

    public function getSourceName() {
        return $this->_sourceName;
    }

    public function setSourceName($sourceName) {
        $this->_sourceName = $sourceName;
    }

    public function getSourceId() {
        return $this->_sourceId;
    }

    public function setSourceId($sourceId) {
        $this->_sourceId = $sourceId;
    }

}

